package com.xiuxia.bopicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiuxia.bopicturebackend.api.aliyunai.AliYunAiApi;
import com.xiuxia.bopicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.xiuxia.bopicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.xiuxia.bopicturebackend.common.ColorSimilarUtils;
import com.xiuxia.bopicturebackend.common.MinIOUtil;
import com.xiuxia.bopicturebackend.config.CosClientConfig;
import com.xiuxia.bopicturebackend.config.MinioConfig;
import com.xiuxia.bopicturebackend.exception.BusinessException;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.exception.ThrowUtils;
import com.xiuxia.bopicturebackend.manager.CosManager;
import com.xiuxia.bopicturebackend.manager.upload.FileUpload;
import com.xiuxia.bopicturebackend.manager.upload.PictureURLUpload;
import com.xiuxia.bopicturebackend.manager.upload.PictureUploadTemplate;
import com.xiuxia.bopicturebackend.mapper.PictureMapper;
import com.xiuxia.bopicturebackend.model.dto.file.UploadPictureResult;
import com.xiuxia.bopicturebackend.model.dto.picture.*;
import com.xiuxia.bopicturebackend.model.entity.Picture;
import com.xiuxia.bopicturebackend.model.entity.Space;
import com.xiuxia.bopicturebackend.model.entity.SpaceUser;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.model.enums.PictureReviewStatusEnum;
import com.xiuxia.bopicturebackend.model.vo.picture.PictureVO;
import com.xiuxia.bopicturebackend.model.vo.user.UserVO;
import com.xiuxia.bopicturebackend.service.PictureService;
import com.xiuxia.bopicturebackend.service.SpaceService;
import com.xiuxia.bopicturebackend.service.SpaceUserService;
import com.xiuxia.bopicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 17732
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-04-29 22:16:56
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Resource
    private UserService userService;
    @Resource
    private FileUpload fileUpload;
    @Resource
    private PictureURLUpload pictureURLUpload;
    @Resource
    private MinIOUtil minIOUtil;
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private CosManager cosManager;
    @Resource
    private ThreadPoolExecutor customExecutor;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private CosClientConfig cosClientConfig;


    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequestDTO pictureUploadRequestDTO, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, new BusinessException(ErrorCode.NO_AUTH_ERROR));
        ThrowUtils.throwIf(pictureUploadRequestDTO == null, ErrorCode.PARAMS_ERROR);
        // 校验空间是否存在
        Long spaceId = pictureUploadRequestDTO.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权限操作该空间");
            ThrowUtils.throwIf(space.getTotalCount() >= space.getMaxCount(), ErrorCode.OPERATION_ERROR, "上传的图片数量已经达到最大");
            ThrowUtils.throwIf(space.getTotalSize() >= space.getMaxSize(), ErrorCode.OPERATION_ERROR, "上传的图片额度已经达到最大");
        }
        //判断是新增还是更新
        Long pictureId = null;
        pictureId = pictureUploadRequestDTO.getId();
        //如果是更新判断图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            //仅本人和管理员可以审核图片
            ThrowUtils.throwIf(!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR);
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                ThrowUtils.throwIf(!oldPicture.getSpaceId().equals(spaceId), ErrorCode.PARAMS_ERROR, "图片空间id不一致");
            }
        }
        // 上传图片，获取图片信息
        String picturePrefix;
        if (spaceId == null) {
            picturePrefix = String.format("public/%s", loginUser.getId());
        } else {
            picturePrefix = String.format("space/%s", spaceId);
        }
        // 根据输入源区分图片上传方式
        PictureUploadTemplate pictureUploadTemplate = fileUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = pictureURLUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, picturePrefix);
        Picture picture = getPicture(loginUser, uploadPictureResult, pictureId, pictureUploadRequestDTO, spaceId);
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId).setSql("totalSize = totalSize + " + picture.getPicSize()).setSql("totalCount = totalCount + 1").update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });

        return PictureVO.objToVo(picture);
    }

    public Picture getPicture(User loginUser, UploadPictureResult uploadPictureResult, Long pictureId, PictureUploadRequestDTO pictureUploadRequestDTO, Long spaceId) {
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setSpaceId(spaceId);
        picture.setPicColor(uploadPictureResult.getPicColor());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setOriginalUrl(uploadPictureResult.getOriginalUrl());
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequestDTO != null && StrUtil.isNotBlank(pictureUploadRequestDTO.getPicName())) {
            picName = pictureUploadRequestDTO.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        // 插入数据库
        if (pictureId != null) {
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        //补充审核参数
        this.fillPictureParam(picture, loginUser);
        return picture;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequestDTO pictureQueryRequest) {
        QueryWrapper<Picture> pictureQueryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return pictureQueryWrapper;
        }
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();


        if (StrUtil.isNotBlank(searchText)) {
            pictureQueryWrapper.and(queryWrapper -> queryWrapper.like("name", searchText).or().like("introduction", searchText));
        }
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        pictureQueryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        pictureQueryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        pictureQueryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        pictureQueryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        pictureQueryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        pictureQueryWrapper.isNull(nullSpaceId, "spaceId");
        pictureQueryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        pictureQueryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                pictureQueryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        pictureQueryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return pictureQueryWrapper;

    }

    @Override
    public void doPictureReview(PictureReviewRequestDTO pictureReviewRequestDTO, User loginUser) {
        //1.校验参数
        ThrowUtils.throwIf(pictureReviewRequestDTO == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        Long id = pictureReviewRequestDTO.getId();
        Integer reviewStatus = pictureReviewRequestDTO.getReviewStatus();
        PictureReviewStatusEnum pictureReviewStatus = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        //不能将图片的状态再修改为待审核
        ThrowUtils.throwIf(id == null || pictureReviewStatus == null || PictureReviewStatusEnum.REVIEWING.equals(pictureReviewStatus), new BusinessException(ErrorCode.PARAMS_ERROR));
        // 确认图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 审核状态是否重复
        ThrowUtils.throwIf(oldPicture.getReviewStatus().equals(reviewStatus), new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核"));
        // 数据库操作
        Picture newPicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequestDTO, newPicture);
        newPicture.setReviewerId(loginUser.getId());
        newPicture.setReviewTime(new Date());
        boolean result = this.updateById(newPicture);
        ThrowUtils.throwIf(!result, new BusinessException(ErrorCode.OPERATION_ERROR));
    }

    @Override
    public void fillPictureParam(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            picture.setReviewerId(loginUser.getId());
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动审核通过");
        } else {
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer pictureUploadByBatch(PictureUploadByBatchRequestDTO pictureUploadByBatchRequestDTO, User loginUser) {
        // 校验参数
        String searchText = pictureUploadByBatchRequestDTO.getSearchText();
        Integer count = pictureUploadByBatchRequestDTO.getCount();
        Integer first = pictureUploadByBatchRequestDTO.getFirst();
        String prefix = pictureUploadByBatchRequestDTO.getPrefix();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多上传30张图片");
        // 抓取内容
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&first=%d&mmasync=1", searchText, first);
        if (StrUtil.isBlank(prefix)) {
            prefix = searchText;
        }
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select(".iusc");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String dataM = imgElement.attr("m");
            String fileUrl;
            try {
                JSONObject jsonObject = JSONUtil.parseObj(dataM);
                fileUrl = jsonObject.getStr("murl");
            } catch (Exception e) {
                log.error("解析图片链接失败", e);
                continue;
            }
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequestDTO pictureUploadRequestDTO = new PictureUploadRequestDTO();
            pictureUploadRequestDTO.setPicName((uploadCount + 1) + "_" + prefix);
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequestDTO, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("url:{},图片上传失败", fileUrl, e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 清理cos中图片
     *
     * @param oldPicture
     */
    @Override
    public void clearPictureFile(Picture oldPicture) {
        String url = oldPicture.getUrl();
        Long count = this.lambdaQuery().eq(Picture::getUrl, url).count();
        if (count > 1) {
            return;
        }
        String key = null;
        key = url.replace(cosClientConfig.getHost(), "");
        cosManager.deleteObject(key);
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotEmpty(thumbnailUrl)) {
            key = thumbnailUrl.replace(cosClientConfig.getHost(), "");
            cosManager.deleteObject(key);
        }
        String originalUrl = oldPicture.getOriginalUrl();
        if (StrUtil.isNotEmpty(originalUrl)) {
            key = originalUrl.replace(cosClientConfig.getHost(), "");
            cosManager.deleteObject(key);
        }
    }

    /**
     * 清理minio中无用的图片文件
     */
   /* @Override
    public void clearPictureFile(Picture oldPicture) {
        String url = oldPicture.getUrl();
        Long count = this.lambdaQuery().eq(Picture::getUrl, url).count();
        if (count > 1) {
            return;
        }
        String objName = url.substring(url.lastIndexOf(minioConfig.getBucket() + "/") + minioConfig.getBucket().length() + 1);
        log.info("删除对象: {}", objName);
        minIOUtil.remove(objName);
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotEmpty(thumbnailUrl)) {
            String thumbnailFileName = thumbnailUrl.substring(thumbnailUrl.lastIndexOf(minioConfig.getBucket() + "/") + minioConfig.getBucket().length() + 1);
            minIOUtil.remove(thumbnailFileName);
        }
        String originalUrl = oldPicture.getOriginalUrl();
        if (StrUtil.isNotEmpty(originalUrl)) {
            String originalFileName = originalUrl.substring(originalUrl.lastIndexOf(minioConfig.getBucket() + "/") + minioConfig.getBucket().length() + 1);
            minIOUtil.remove(originalFileName);
        }
    }*/
    @Override
    public List<Picture> getDeletedPictureList() {
        return this.baseMapper.getDeletedPictureList();
    }

    @Override
    public Boolean deletePicture(Long pictureId, User loginUser) {
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
//        checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate().eq(Space::getId, spaceId).setSql("totalSize = totalSize - " + oldPicture.getPicSize()).setSql("totalCount = totalCount - 1").update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(oldPicture);
        return true;
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            //公共图库仅本人和管理员可以操作
            ThrowUtils.throwIf(!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR);
        } else {
            //私有空间，仅创建者可以操作
            ThrowUtils.throwIf(!picture.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR);
        }

    }

    @Override
    public void editPicture(PictureEditRequestDTO pictureEditRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditRequest == null || pictureEditRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureEditRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        picture.setEditTime(new Date());
        this.validPicture(picture);
        User loginUser = userService.getLoginUser(request);
        long id = pictureEditRequest.getId();
        // 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //仅本人或管理员可编辑
//        this.checkPictureAuth(loginUser, oldPicture);
        this.fillPictureParam(picture, loginUser);
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "没有空间权限");
        List<Picture> pictureList = this.lambdaQuery().eq(Picture::getSpaceId, spaceId).isNotNull(Picture::getPicColor).list();
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        Color targetColor = Color.decode(picColor);
        List<Picture> sortedPictures = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
            String hexColor = picture.getPicColor();
            if (StrUtil.isBlank(hexColor)) {
                return Double.MAX_VALUE;
            }
            Color pictureColor = Color.decode(hexColor);
            return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
        })).limit(12).collect(Collectors.toList());
        return sortedPictures.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchEditPicture(PictureEditByBatchRequestDTO pictureEditByBatchRequestDTO, User loginUser) {
        validateBatchEditRequest(pictureEditByBatchRequestDTO, loginUser);
        List<Picture> pictureList = this.lambdaQuery().eq(Picture::getSpaceId, pictureEditByBatchRequestDTO.getSpaceId()).in(Picture::getId, pictureEditByBatchRequestDTO.getPictureIdList()).list();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureList), ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        // 批量重命名
        String nameRule = pictureEditByBatchRequestDTO.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        int batchSize = 100;
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i += batchSize) {
            List<Picture> pictures = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                for (Picture picture : pictures) {
                    if (pictureEditByBatchRequestDTO.getCategory() != null) {
                        picture.setCategory(pictureEditByBatchRequestDTO.getCategory());
                    }
                    if (pictureEditByBatchRequestDTO.getTags() != null) {
                        picture.setTags(JSONUtil.toJsonStr(pictureEditByBatchRequestDTO.getTags()));
                    }
                }
                boolean result = this.updateBatchById(pictures);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量更新图片失败");

            }, customExecutor);
            futures.add(future);
        }
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }

    @Override
    public void deletePictureByBatch(PictureDeleteByBatchRequestDTO deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        List<Long> pictureIdList = deleteRequest.getPictureIdList();
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        Long spaceId = deleteRequest.getSpaceId();
        if (spaceId == null) {
            ThrowUtils.throwIf(!userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "你没有权限删除公共图片");
            boolean result = this.removeBatchByIds(pictureIdList);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除图片失败");
        } else {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            boolean result = this.removeBatchByIds(pictureIdList);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除图片失败");
        }
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId)).orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
//        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }


    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }


    private void validateBatchEditRequest(PictureEditByBatchRequestDTO pictureEditByBatchRequestDTO, User loginUser) {
        ThrowUtils.throwIf(pictureEditByBatchRequestDTO == null, ErrorCode.PARAMS_ERROR);
        List<Long> pictureIdList = pictureEditByBatchRequestDTO.getPictureIdList();
        Long spaceId = pictureEditByBatchRequestDTO.getSpaceId();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList) || spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "没有空间权限");
    }
}




